<template>
  <a-modal
    :open="props.open"
    :title="`${props.title}`"
    width="600px"
    destroy-on-close
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div class="add-edit-modal">
      <a-form ref="formRef" :layout="'vertical'" :model="formState" :rules="rules">
        <a-form-item label="组织名称" name="orgName">
          <a-input v-model:value="formState.orgName" class="w-520" placeholder="请输入组织名称" :maxlength="200" />
        </a-form-item>

        <a-form-item label="组织类型" name="level">
          <a-radio-group v-model:value="formState.level" :disabled="props.id ? true : false" class="w-520" placeholder="请输入组织类型">
            <a-radio :value="2">学院</a-radio>
            <a-radio :value="3">专业</a-radio>
            <a-radio :value="4">学级</a-radio>
            <a-radio :value="5">班级<span class="radio-tips"> (学生绑定在此类型的组织上)</span></a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="上级组织" name="parentId">
          <a-tree-select
            v-model:value="formState.parentId"
            allow-clear
            tree-default-expand-all
            :field-names="{
              children: 'children',
              label: 'orgName',
              value: 'id'
            }"
            :tree-data="transformedTreeData"
            tree-node-filter-prop="label"
            placeholder="请输入上级组织"
            class="w-520"
          />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { FormInstance, message } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { computed, onMounted, reactive, ref } from 'vue'

  import { schoolOrganizationManageApi } from '@/services/api/aigc-admin'
  import { countStrToBit, validateDirName } from '@/utils'
  import { regex } from '@/utils/regex'

  import { FormState, treeDataType } from '../types/index'
  const props = defineProps({
    title: {
      type: String,
      default: '新建组织'
    },
    open: {
      type: Boolean,
      default: false
    },
    id: {
      required: false,
      type: String,
      default: ''
    },
    addChildId: {
      required: false,
      type: String,
      default: ''
    }
  })

  const emits = defineEmits<{ (e: 'ok'): void; (e: 'cancel'): void }>()

  const formState = reactive<FormState>({
    orgName: '',
    id: '',
    level: 2,
    parentId: ''
  })
  const validateByte = async (rule: Rule, value: string) => {
    const byteCount = countStrToBit(value)
    if (byteCount === 0) {
      return Promise.reject('请输入组织名称')
    } else if (byteCount > 200) {
      return Promise.reject('名称不可超过200字节')
    }
    return Promise.resolve()
  }
  const rules: Record<string, Rule[]> = {
    orgName: [{ required: true, pattern: regex.CHENNumber, trigger: 'change', message: '请输入组织名称，仅支持中英文、数字' }],
    level: [{ required: true, message: '请选择组织类型', trigger: 'change' }],
    parentId: [{ required: true, message: '请选择上级组织', trigger: 'change' }]
  }
  const formRef = ref<FormInstance>()

  const treeData = ref<treeDataType[]>([])
  const confirmLoading = ref<boolean>(false)
  const handleOk = async () => {
    confirmLoading.value = true
    try {
      await formRef.value?.validate()
      if (props.id) {
        const { code } = await schoolOrganizationManageApi.edit(formState)

        success(code)
        message.success('编辑成功')
      } else {
        const { code } = await schoolOrganizationManageApi.add(formState)

        success(code)
        message.success('新增成功')
      }

      confirmLoading.value = false
    } catch (error) {
      confirmLoading.value = false
    }
  }

  // 成功后
  const success = (code: string) => {
    if (code === 'SYSTEM-100000') {
      emits('ok')
      formRef.value?.resetFields()
    }
  }

  // 获取组织架构
  const getTree = async () => {
    const { data } = await schoolOrganizationManageApi.getOrganizationTree({ authFlag: 1 })
    treeData.value = data
  }
  const transformTreeData = (data: any[]): any[] => {
    return data.map(item => ({
      ...item,
      disabled: !item.isAuthActive || item.level === 5,
      children: item.children ? transformTreeData(item.children) : []
    }))
  }

  const transformedTreeData = computed(() => transformTreeData(treeData.value))
  const handleCancel = () => {
    formRef.value?.resetFields()
    // formState = {}
    emits('cancel')
  }

  // 获取详情
  const getDetail = async (): Promise<void> => {
    const { data } = await schoolOrganizationManageApi.detail(props.id)()
    console.log('获取详情:', data)

    formState.orgName = data.orgName
    formState.parentId = data.parentId
    formState.id = data.id
    formState.level = data.level
  }
  // watch(
  //   () => props.open,
  //   () => {
  //     if (props.open) {
  //       getTree()
  //       if (props.id) {
  //         getDetail()
  //       }
  //       if (props.addChildId) {
  //         console.log('props:', props)

  //         formState.parentId = props.addChildId
  //       }
  //     }
  //   }
  // )
  onMounted(() => {
    // 		if(props.id) {
    console.log('props:', props.id)

    getTree()
    if (props.id) {
      getDetail()
    }
    if (props.addChildId) {
      console.log('props:', props)

      formState.parentId = props.addChildId
    }
    // getDetail()
    // 		}
  })
</script>

<style lang="less" scoped>
  .add-edit-modal {
    .radio-tips {
      font-size: 12px;
      color: rgba(17, 22, 31, 0.29);
    }
  }
</style>
